//
// Created by admin on 2016/4/29.
//
#include "helo.h"
#include <cstdio>
#include <android/log.h>

//修改日志tag中的值
#define LOG_TAG "helo.cpp"
//#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
//#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define JNI_CLASS_NAME "com/mrper/jnindk/MainActivity"  //定义Native类

//要注册的方法名及签名：  name - sign - methodsName
static JNINativeMethod jniMethods[] = {
        {
                "add",
                "(II)I",
                (void *) add
        },
        {
                "factory",
                "(I)I",
                (void *) factory
        },
        {
                "getDomainUrl",
                "()Ljava/lang/String;",
                (void *) getDomainUrl
        },
        {
                "showToast",
                "(Ljava/lang/String;)V",
                (void *) showToast
        }
};

jint JNI_OnLoad(JavaVM *vm, void *reserved) {
    jint result = -1;
    JNIEnv *env = NULL;
    if (vm->GetEnv((void **) &env, JNI_VERSION_1_6)) {
        goto fail;
    }
    if (registerNatives(env, JNI_CLASS_NAME) != JNI_TRUE) {
        goto fail;
    }
    result = JNI_VERSION_1_6;
    fail:
    return result;
}

static int registerNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *methods,
                                 int numMethods) {
    jclass clazz;
    clazz = env->FindClass(className);
    if (clazz == NULL) {
        return JNI_FALSE;
    }
    if (env->RegisterNatives(clazz, methods, numMethods) < 0) {
        return JNI_FALSE;
    }
    return JNI_TRUE;
}

static int registerNatives(JNIEnv *env, const char *className) {
    if (!registerNativeMethods(env, className, jniMethods,
                               sizeof(jniMethods) / sizeof(jniMethods[0]))) {
        return JNI_FALSE;
    }
    return JNI_TRUE;
}

jint add(JNIEnv *env, jobject thiz, jint a, jint b) {
    return a + b;
}


jint factory(JNIEnv *env, jobject thiz, jint a) {
    if (a < 1) {
//        LOGD("value is not smaller than 1");
        return -1;
    }
    jint value = 1;
    while (a > 1) {
        value *= a;
        a--;
    }
    return value;
}

jstring getDomainUrl(JNIEnv *env, jobject thiz) {
    return env->NewStringUTF("http://www.baidu.com/");
}

/**
 * 显示Tast弹窗
 * env
 * thiz 类对象
 * message 消息内容
 */
void showToast(JNIEnv *env, jobject thiz, jstring message) {
    jclass toastClass = env->FindClass("android/widget/Toast");
    if (toastClass != NULL) {
        jmethodID mid = env->GetStaticMethodID(toastClass, "makeText",
                                               "(Landroid/content/Context;Ljava/lang/CharSequence;I)Landroid/widget/Toast;");
        jobject toastObj = env->CallStaticObjectMethod(toastClass, mid, thiz, message, 1000);
        jmethodID showMid = env->GetMethodID(toastClass, "show", "()V");
        env->CallVoidMethod(toastObj, showMid);
    }else{
//        LOGI("Cann't find Toast class");
    }
}
